<?php
/*-------------------------------------------------------------------------\
|
|  ========================================================
|  Fusion Registry GPL
|  Copyright (C) 2007 Fusion Scripts
|
|  This program is free software; you can redistribute it and/or
|  modify it under the terms of the GNU General Public License
|  as published by the Free Software Foundation; either version 2
|  of the License, or (at your option) any later version.
|
|  This program is distributed in the hope that it will be useful,
|  but WITHOUT ANY WARRANTY; without even the implied warranty of
|  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
|  GNU General Public License for more details.
|
|  You should have received a copy of the GNU General Public License
|  along with this program; if not, write to the Free Software
|  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
|  ========================================================
|
|  Email: info@fusionscripts.com
|  Web-Site: http://www.fusionscripts.com/
|
|  $Id: ad_makes_models.php 4 2008-08-03 01:43:03Z registry.fusion $
|
\-------------------------------------------------------------------------*/

/**
 * This is the admin interface for vehicle makes & models of the Fusion Registry
 *
 * @package Fusion Registry
 * @subpackage admin
 * @version $Id: ad_makes_models.php 4 2008-08-03 01:43:03Z registry.fusion $
 */

if ( ! defined( 'AD_REGISTRY_CALLED' ) )
{
    print "<h1>Incorrect access</h1>You cannot access this file directly.";
    exit();
}

/**
 * Fusion Registry requires
 */
require_once( AD_REGISTRY_PATH.'ad_registry_loader.php' );
require_once( REGISTRY_PATH.'lib/custom_fields.php' );

/**
 * Class ad_registry_makes_models deals with the vehicle makes & models of the Fusion Registry
 *
 * @package Fusion Registry
 * @subpackage admin
 */
class ad_registry_makes_models
{
    var $ipsclass;

    /** @var string */
    var $base_url;

    /** @var object */
    var $ad_registry_loader;

    /** @var array Libraries */
    var $lib = array();

    /**
     * Intialization of ad_registry_makes_models
     *
     * Another traffic cop function, there should be minimal procedural code
     * here.
     *
     * @global array
     */
    function auto_run()
    {
        // Kill globals - globals bad, Homer good.
        $tmp_in = array_merge( $_GET, $_POST, $_COOKIE );

        foreach ( $tmp_in as $k => $v )
        {
            unset($$k);
        }

        // Initialize ad_registry_loader
        $this->ad_registry_loader = new ad_registry_loader();
        $this->ad_registry_loader->ipsclass =& $this->ipsclass;
        $this->ad_registry_loader->auto_run(&$this);

        // Initialize custom_fields
        $this->lib['custom_fields'] = new registry_custom_fields(&$class);
        $this->lib['custom_fields']->ipsclass =& $this->ipsclass;

        switch($this->ipsclass->input['code'])
        {
            case 'add_make':
                $this->add_make();
                break;

            case 'add_model':
                $this->add_model();
                break;

            case 'delete_make_menu':
                $this->delete_make_menu();
                break;

            case 'delete_make':
                $this->delete_make();
                break;

            case 'delete_model_menu':
                $this->delete_model_menu();
                break;

            case 'delete_model':
                $this->delete_model();
                break;

            case 'model_menu':
                $this->model_menu();
                break;

            case 'modify_make':
                $this->modify_make();
                break;

            case 'modify_model':
                $this->modify_model();
                break;

            default:
                $this->make_menu();
                break;
        }
    }


    /**
     * Add new vehicle make(s)
     *
     * Take user input and add new entries in the database, multiple
     * values are split on the HTML br tag.
     */
    function add_make()
    {
        if ($this->ipsclass->input['new_makes'] == "")
        {
            $this->ipsclass->admin->error("You must enter at least one Vehicle Make.");
        }

        // Handle possible multiple entries
        $new_makes = explode('<br />', $this->ipsclass->input['new_makes']);

        $added_makes = '';

        foreach ( $new_makes as $make )
        {
            // Remove trailing whitespace
            $make = rtrim($make);

            // Skip blank lines
            if ( empty($make) )
            {
                continue;
            }

            // Create the db insert string
            $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'make' => $make ) );

            // Add the make
            $this->ipsclass->DB->query("INSERT INTO ibf_registry_makes (".$db_string['FIELD_NAMES'].") VALUES(".$db_string['FIELD_VALUES'].")");

            $added_makes .= "$make, ";
        }

        $added_makes = substr($added_makes, 0, -2);

        $text = "Added Fusion Registry Vehicle Make(s) '$added_makes'";
        $url = 'act='.REGISTRY_URL.'&section=components&menu=makes_models';
        $time = 2;

        // Big brother is watching :)
        $this->ipsclass->admin->save_log($text);

        // End of the show, c'ya
        $this->ipsclass->admin->redirect( $url, $text, 0, $time );
    }


    /**
     * Add new vehicle model(s)
     *
     * Take user input and add new entries in the database, multiple
     * values are split on the HTML br tag.
     */
    function add_model()
    {
        if ($this->ipsclass->input['new_models'] == "")
        {
            $this->ipsclass->admin->error("You must enter at least one Vehicle Model.");
        }

        // Handle possible multiple entries
        $new_models = explode('<br />', $this->ipsclass->input['new_models']);

        $added_models = '';

        foreach ( $new_models as $model )
        {
            // Remove trailing whitespace
            $model = rtrim($model);

            // Skip blank lines
            if ( empty($model) )
            {
                continue;
            }

            // Create the db insert string
            $db_string = $this->ipsclass->DB->compile_db_insert_string( array( 'model' => $model,
                                                                               'make_id' => $this->ipsclass->input['make_id'],
                                                                      )      );

            // Add the make
            $this->ipsclass->DB->query("INSERT INTO ibf_registry_models (".$db_string['FIELD_NAMES'].") VALUES(".$db_string['FIELD_VALUES'].")");

            $added_models .= "$model, ";
        }

        $added_models = substr($added_models, 0, -2);

        $text = "Added Fusion Registry Vehicle Model(s) '$added_models'";
        $url = 'act='.REGISTRY_URL.'&section=components&menu=makes_models&code=model_menu&make_id='. $this->ipsclass->input['make_id'];
        $time = 2;

        // Big brother is watching :)
        $this->ipsclass->admin->save_log($text);

        // End of the show, c'ya
        $this->ipsclass->admin->redirect( $url, $text, 0, $time );
    }


    /**
     * Display HTML vehicle make configuration menu
     *
     * This screen allows users to rename/edit/delete and bulk add
     * vehicles makes to the Fusion Registry.
     */
    function make_menu()
    {
        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( "Fusion Registry Vehicle Makes", "You may add/rename/delete Fusion Registry Vehicle Makes below.<br /><br /><b>NOTE:</b> This section of the ACP is targeted towards vehicle based registries.<br />If you do not run a vehicle based registry you can ignore this section of the ACP entirely.".'<br />&nbsp;' ) . "<br >";

        //------------------------------
        // Add new Make Form
        //------------------------------
        $code = "add_make";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code', $code          ),
                                                                             2 => array( 'menu', 'makes_models' ),
                                                                             3 => array( 'act', REGISTRY_URL    ),
                                                                             4 => array( 'section', 'components' ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "20%" );
        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "80%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Add New Make(s)" );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Vehicle Make(s)</b><br /><div style='color:grey'>Enter one per line.</div>",
                                                                             $this->ipsclass->adskin->form_textarea('new_makes'),
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form( "Add Make(s)" );
        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        //------------------------------
        // Make Control Form
        //------------------------------
        $code = "delete_make_menu";

        $this->ipsclass->html .= <<<JAVASCRIPT
<script type="text/javascript">
<!--
function rename_make( make_id, make_name )
{
    var inputedData = prompt("Rename make '" + make_name + "' to what?", "");

    if ( inputedData == "" || inputedData == null )
    {
        alert("You did not enter a value, canceling!");
    }
    else
    {
        if ( confirm("Are you sure you want to rename make '" + make_name + "' to '" + inputedData + "'") )
        {
            location.href = "{$this->ipsclass->base_url}&act=
JAVASCRIPT;

        $this->ipsclass->html .= REGISTRY_URL;
        $this->ipsclass->html .= <<<JAVASCRIPT
&section=components&menu=makes_models&code=modify_make&make_id=" + make_id + "&change_to=" + inputedData;
        }
    }
}

function select_all() {
    for (var i=0;i<document.make_management.elements.length;i++)
    {
       var e = document.make_management.elements[i];
       if (e.type=='checkbox')
       {
          if (e.checked == false) {
               e.checked = true;
          }
          else
               e.checked = false;
          }
     }
     return 1;
}
//-->
</script>
JAVASCRIPT;

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code', $code          ),
                                                                             2 => array( 'menu', 'makes_models' ),
                                                                             3 => array( 'act' , REGISTRY_URL   ),
                                                                             4 => array( 'section', 'components' ),
                                                                           ),
                                                                      'make_management'
                                                                    );

        $this->ipsclass->adskin->td_header[] = array( "<a href='#' onClick='select_all();return false;'>Select</a>" , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Rename" , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Delete" , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "ID"     , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Name"   , "70%" );
        $this->ipsclass->adskin->td_header[] = array( "Models" , "6%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Vehicle Make Management" );

        // Grab the current makes
        $this->ipsclass->DB->query("SELECT id, make FROM ibf_registry_makes ORDER BY `make` ASC");

        // Build our control html
        while ( $registry_make = $this->ipsclass->DB->fetch_row() )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( '<center>'. $this->ipsclass->adskin->form_checkbox( 'make_id[]', '0', $registry_make['id'] ) .'</center>',
                                                                                 "<center><b><a href='#' onClick=\"rename_make('". $registry_make['id'] ."', '". $registry_make['make'] ."'); return false;\">". $this->ad_registry_loader->imgs['edit'] ."</a></b></center>",
                                                                                 "<center><b><a href='{$this->ipsclass->base_url}&act=".REGISTRY_URL."&section=components&menu=makes_models&code=delete_make_menu&make_id=". $registry_make['id'] ."'>". $this->ad_registry_loader->imgs['delete'] ."</a></b></center>",
                                                                                 '<center>'. $registry_make['id'] .'</center>',
                                                                                 $registry_make['make'],
                                                                                 "<center><b><a href='{$this->ipsclass->base_url}&act=".REGISTRY_URL."&section=components&menu=makes_models&code=model_menu&make_id=". $registry_make['id'] ."'>". $this->ad_registry_loader->imgs['folder_arrow'] ."</a></b></center>",
                                                                        )      );
        }

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form( "Delete Selected Make(s)" );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $this->ipsclass->admin->nav[] = array( '', 'Fusion Registry Vehicle Makes' );

        // That's is Folks!
        $this->ipsclass->admin->output();
    }


    /**
     * Display HTML vehicle models configuration menu
     *
     * This screen allows users to rename/edit/delete and bulk add
     * vehicle models of a specific vehicle make.
     */
    function model_menu()
    {
        // Get the make name for the id passed
        if ( $this->ipsclass->input['make_id'] == "" )
        {
            $this->ipsclass->admin->error("Could not determine the Fusion Registry Vehicle Make ID.");
        }

        $this->ipsclass->DB->query("SELECT make FROM ibf_registry_makes WHERE id='".$this->ipsclass->input['make_id']."'");
        $make = $this->ipsclass->DB->fetch_row();

        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( "Fusion Registry `". $make['make'] ."` Models", "You may add/rename/delete Fusion Registry Vehicle Models below.".'<br />&nbsp;' ) . "<br >";

        //------------------------------
        // Add new Model Form
        //------------------------------
        $code = "add_model";

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code'   , $code                       ),
                                                                             2 => array( 'act'    , REGISTRY_URL                ),
                                                                             3 => array( 'make_id', $this->ipsclass->input['make_id'] ),
                                                                             4 => array( 'menu'   , 'makes_models'              ),
                                                                             5 => array( 'section', 'components'                ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "20%" );
        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "80%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "Add New `". $make['make'] ."` Model(s)" );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Vehicle Model(s)</b><br /><div style='color:grey'>Enter one per line.</div>",
                                                                              $this->ipsclass->adskin->form_textarea('new_models'),
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form( "Add Model(s)" );
        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        //------------------------------
        // Make Control Form
        //------------------------------
        $code = "delete_model_menu";

        $this->ipsclass->html .= <<<JAVASCRIPT
<script type="text/javascript">
<!--
function rename_model( model_id, model_name )
{
    var inputedData = prompt("Rename model '" + model_name + "' to what?", "");

    if ( inputedData == "" || inputedData == null )
    {
        alert("You did not enter a value, canceling!");
    }
    else
    {
        if ( confirm("Are you sure you want to rename model '" + model_name + "' to '" + inputedData + "'") )
        {
            location.href = "{$this->ipsclass->base_url}&act=
JAVASCRIPT;

        $this->ipsclass->html .= REGISTRY_URL;
        $this->ipsclass->html .= <<<JAVASCRIPT
&section=components&menu=makes_models&code=modify_model&make_id={$this->ipsclass->input['make_id']}&model_id=" + model_id + "&change_to=" + inputedData;
        }
    }
}

function select_all() {
    for (var i=0;i<document.model_management.elements.length;i++)
    {
       var e = document.model_management.elements[i];
       if (e.type=='checkbox')
       {
          if (e.checked == false) {
               e.checked = true;
          }
          else
               e.checked = false;
          }
     }
     return 1;
}
//-->
</script>
JAVASCRIPT;

        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code'   , $code                       ),
                                                                             2 => array( 'act'    , REGISTRY_URL                ),
                                                                             3 => array( 'make_id', $this->ipsclass->input['make_id'] ),
                                                                             4 => array( 'menu'   , 'makes_models'              ),
                                                                             5 => array( 'section', 'components'                ),
                                                                           ),
                                                                      'model_management'
                                                                    );

        $this->ipsclass->adskin->td_header[] = array( "<a href='#' onClick='select_all();return false;'>Select</a>" , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Rename" , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Delete" , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "ID"     , "6%" );
        $this->ipsclass->adskin->td_header[] = array( "Name"   , "76%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( "`". $make['make'] ."` Model Management" );

        // Grab the models for this make
        $this->ipsclass->DB->query("SELECT id, model FROM ibf_registry_models WHERE make_id = '". $this->ipsclass->input['make_id'] ."' ORDER BY model ASC");

        // Build our array of models
        while ( $registry_model = $this->ipsclass->DB->fetch_row() )
        {
            $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( '<center>'. $this->ipsclass->adskin->form_checkbox( 'model_id[]', '0', $registry_model['id'] ) .'</center>',
                                                                                 "<center><b><a href='#' onClick=\"rename_model('". $registry_model['id'] ."', '". $registry_model['model'] ."'); return false;\">". $this->ad_registry_loader->imgs['edit'] ."</a></b></center>",
                                                                                 "<center><b><a href='{$this->ipsclass->base_url}&act=".REGISTRY_URL."&section=components&menu=makes_models&code=delete_model_menu&model_id=". $registry_model['id'] ."&make_id=". $this->ipsclass->input['make_id'] ."'>". $this->ad_registry_loader->imgs['delete'] ."</a></b></center>",
                                                                                 '<center>'. $registry_model['id'] .'</center>',
                                                                                 $registry_model['model'],
                                                                        )      );
        }

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form( "Delete Selected Model(s)" );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $this->ipsclass->admin->nav[] = array( 'act='.REGISTRY_URL.'&section=components&menu=makes_models', 'Fusion Registry Vehicle Makes' );
        $this->ipsclass->admin->nav[] = array( '', 'Models' );

        // That's is Folks!
        $this->ipsclass->admin->output();
    }


    /**
     * Modify existing vehicle make
     *
     * On the client side javascript is in charge of the interface to
     * prompt the user for input.
     */
    function modify_make()
    {
        if ($this->ipsclass->input['change_to'] == "")
        {
            $this->ipsclass->admin->error("You must enter a new Vehicle Make.");
        }

        // Create the db update string
        $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'make' => $this->ipsclass->input['change_to'] ) );

        $this->ipsclass->DB->query("UPDATE ibf_registry_makes SET $db_string WHERE id='".$this->ipsclass->input['make_id']."'");

        $text = "Modified Fusion Registry Make ID: '{$this->ipsclass->input['make_id']}' to '{$this->ipsclass->input['change_to']}'";
        $url = 'act='.REGISTRY_URL.'&section=components&menu=makes_models&code=make_menu';
        $time = 2;

        // Big brother is watching :)
        $this->ipsclass->admin->save_log($text);

        // End of the show, c'ya
        $this->ipsclass->admin->redirect( $url, $text, 0, $time );
    }


    /**
     * Modify existing vehicle model
     *
     * On the client side javascript is in charge of the interface to
     * prompt the user for input.
     */
    function modify_model()
    {
        if ($this->ipsclass->input['change_to'] == "")
        {
            $this->ipsclass->admin->error("You must enter a new Vehicle Model.");
        }

        // Create the db update string
        $db_string = $this->ipsclass->DB->compile_db_update_string( array( 'model' => $this->ipsclass->input['change_to'] ) );

        $this->ipsclass->DB->query("UPDATE ibf_registry_models SET $db_string WHERE id='".$this->ipsclass->input['model_id']."'");

        $text = "Modified Fusion Registry Model ID: '{$this->ipsclass->input['model_id']}' to '{$this->ipsclass->input['change_to']}'";
        $url = 'act='.REGISTRY_URL.'&section=components&menu=makes_models&code=model_menu&make_id='. $this->ipsclass->input['make_id'];
        $time = 2;

        // Big brother is watching :)
        $this->ipsclass->admin->save_log($text);

        // End of the show, c'ya
        $this->ipsclass->admin->redirect( $url, $text, 0, $time );
    }


    /**
     * Build the HTML for deleting a make
     *
     * Since we need to know what to do with the models of the make
     * being deleted we need this menu to prompt the user.
     */
    function delete_make_menu()
    {
        $makes_array = array();

        // Do we have a valid make id to delete?
        if ($this->ipsclass->input['make_id'] == "")
        {
            $this->ipsclass->admin->error("Could not determine the Fusion Registry Make ID to delete.");
        }

        // Grab the current makes
        $this->ipsclass->DB->query("SELECT id, make FROM ibf_registry_makes ORDER BY `make` ASC");

        // Make sure we have more than 1 make
        if ($this->ipsclass->DB->get_num_rows() < 2)
        {
            $this->ipsclass->admin->error("Can not delete this Fusion Registry Make, please create another before attempting to delete this one");
        }

        // Clean up array
        if ( is_array($this->ipsclass->input['make_id']) )
        {
            $this->ipsclass->input['make_id'] = array_values($this->ipsclass->input['make_id']);
        }

        $name = '';

        // Build our array of data
        while ( $registry_make = $this->ipsclass->DB->fetch_row() )
        {
            if ( is_array($this->ipsclass->input['make_id']) )
            {
                if ( in_array( $registry_make['id'], $this->ipsclass->input['make_id'] ) )
                {
                    $name .= $registry_make['make'] .', ';
                    continue;
                }
            }
            else
            {
                if ( $registry_make['id'] == $this->ipsclass->input['make_id'] )
                {
                    $name = $registry_make['make'];
                    continue;
                }
            }

            $makes_array[] = array( $registry_make['id'], $registry_make['make'] );
        }

        // Check for at least one make left standing
        if ( count($makes_array) < 1 )
        {
            $this->ipsclass->admin->error("Can not delete the Fusion Registry Make(s), there needs to be at least one Vehicle Make remaining in the database.");
        }

        // Remove trailing comma if needed, implode array for next form
        if ( is_array($this->ipsclass->input['make_id']) )
        {
            $name = substr($name, 0, -2);
            $this->ipsclass->input['make_id'] = implode(',', $this->ipsclass->input['make_id']);
        }

        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( "Removing Fusion Registry Make(s)", $this->ad_registry_loader->imgs['warning'] ."&nbsp;Before we delete the Fusion Registry Vehicle Make(s), we need to determine what to do with any vehicles that may be associated to the Make(s).  Please note that during this process all models belonging to the make(s) will also be deleted. Any vehicles that are associated to those models will have their Models un-associated and will need to be updated.".'<br />&nbsp;' ) . "<br >";

        // Build the HTML
        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code'   , 'delete_make'               ),
                                                                             2 => array( 'act'    , REGISTRY_URL                ),
                                                                             3 => array( 'make_id', $this->ipsclass->input['make_id'] ),
                                                                             4 => array( 'menu'   , 'makes_models'              ),
                                                                             5 => array( 'section', 'components' ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "40%" );
        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "60%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( 'Required' );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Vehicle Make(s) to Delete: </b>" , $name ) );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Change all <i>existing vehicles of this Make(s)</i> to which Make?</b>" ,
                                                                             $this->ipsclass->adskin->form_dropdown( "move_make_id", $makes_array )
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form("Update Vehicles and delete the Make(s)");

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $this->ipsclass->admin->nav[] = array( 'act='.REGISTRY_URL.'&section=components&menu=makes_models', 'Fusion Registry Vehicle Makes' );
        $this->ipsclass->admin->nav[] = array( '', 'Delete Make(s)' );

        // That's all folks!
        $this->ipsclass->admin->output();
    }


    /**
     * Delete a vehicle make(s)
     *
     * Multiple values are split on ',' (comma)
     */
    function delete_make()
    {
        // Do we have a valid source?
        if ($this->ipsclass->input['make_id'] == "")
        {
            $this->ipsclass->admin->error("Could not determine the source Fusion Registry Vehicle Make ID(s).");
        }

        // How about a valid destination?
        if ($this->ipsclass->input['move_make_id'] == "")
        {
            $this->ipsclass->admin->error("Could not determine the destination Fusion Registry Vehicle Make ID.");
        }

        // Extract possible multi-ids
        $make_ids = explode(',', $this->ipsclass->input['make_id']);

        // Make our sql safe ID list
        $sql_make_ids = "('". implode("','", $make_ids) ."')";

        // Grab the Make(s) being deleted
        $this->ipsclass->DB->query("SELECT make FROM ibf_registry_makes WHERE id IN $sql_make_ids");

        $make_to_delete = '';

        while ( $row = $this->ipsclass->DB->fetch_row() )
        {
            $make_to_delete .= $row['make'] .', ';
        }

        $make_to_delete = substr($make_to_delete, 0, -2);

        // Get our custom field def for the make field
        $cf_def = $this->lib['custom_fields']->get_cf_defs( array('WHERE' => "field_options='make'") );

        // It will/should be are first and only returned value!
        $make_def = array_shift($cf_def);

        // Update the existing Vehicles
        $this->ipsclass->DB->query("UPDATE ibf_registry_field_entries SET field_value='".$this->ipsclass->input['move_make_id']."'
                                    WHERE field_value IN $sql_make_ids AND field_id='". $make_def['field_id'] ."'");

        // Bye-Bye... delete the make
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_makes WHERE id IN $sql_make_ids");

        // Delete any models of this make
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_models WHERE make_id IN $sql_make_ids");

        $text = "Deleted Fusion Registry Vehicle Make '$make_to_delete' and Models";
        $url = 'act='.REGISTRY_URL.'&section=components&menu=makes_models&code=make_menu';
        $time = 2;

        // Big brother is watching :)
        $this->ipsclass->admin->save_log($text);

        // End of the show, c'ya
        $this->ipsclass->admin->redirect( $url, $text, 0, $time );
    }


    /**
     * Build the HTML form for deleting a model
     *
     * Since we need to know what to do with the vehicles that belong
     * to the model being deleted we need this menu to prompt the user.
     */
    function delete_model_menu()
    {
        $models_array = array();

        // Do we have a valid model id to delete?
        if ($this->ipsclass->input['model_id'] == "")
        {
            $this->ipsclass->admin->error("Could not determine the Fusion Registry Model ID to delete.");
        }

        // Grab the models for this make
        $this->ipsclass->DB->query("SELECT id, model FROM ibf_registry_models WHERE make_id = '". $this->ipsclass->input['make_id'] ."' ORDER BY model ASC");

        // Make sure we have more than 1 model
        if ($this->ipsclass->DB->get_num_rows() < 2)
        {
            $this->ipsclass->admin->error("Can not delete this Fusion Registry Model, please create another before attempting to delete this one.  If you are trying to delete the last model of a make, you may do so by deleting the make instead.");
        }

        // Clean up array
        if ( is_array($this->ipsclass->input['model_id']) )
        {
            $this->ipsclass->input['model_id'] = array_values($this->ipsclass->input['model_id']);
        }

        $name = '';

        // Build our array of data
        while ( $registry_model = $this->ipsclass->DB->fetch_row() )
        {
            if ( is_array($this->ipsclass->input['model_id']) )
            {
                if ( in_array( $registry_model['id'], $this->ipsclass->input['model_id'] ) )
                {
                    $name .= $registry_model['model'] .', ';
                    continue;
                }
            }
            else
            {
                if ($registry_model['id'] == $this->ipsclass->input['model_id'])
                {
                    $name = $registry_model['model'];
                    continue;
                }
            }

            $models_array[] = array( $registry_model['id'], $registry_model['model']);
        }

        // Check for at least one make left standing
        if ( count($models_array) < 1 )
        {
            $this->ipsclass->admin->error("Can not delete the Fusion Registry Model(s), there needs to be at least one Vehicle Model remaining in the database. If you are trying to delete the last model of a make, you may do so by deleting the make instead.");
        }

        // Remove trailing comma if needed, implode array for next form
        if ( is_array($this->ipsclass->input['model_id']) )
        {
            $name = substr($name, 0, -2);
            $this->ipsclass->input['model_id'] = implode(',', $this->ipsclass->input['model_id']);
        }

        $this->ipsclass->html .= $this->ipsclass->skin_acp_global->information_box( "Removing Fusion Registry Vehicle Model(s)", $this->ad_registry_loader->imgs['warning'] ."&nbsp;Before we delete this Fusion Registry Vehicle Model, we need to determine what to do with any vehicles that may be associated to this Model.".'<br />&nbsp;' ) . "<br >";

        // Build the HTML
        $this->ipsclass->html .= $this->ipsclass->adskin->start_form( array( 1 => array( 'code'    , 'delete_model'               ),
                                                                             2 => array( 'act'     , REGISTRY_URL                 ),
                                                                             3 => array( 'model_id', $this->ipsclass->input['model_id'] ),
                                                                             4 => array( 'make_id' , $this->ipsclass->input['make_id']  ),
                                                                             5 => array( 'menu'    , 'makes_models'               ),
                                                                             6 => array( 'section' , 'components'                 ),
                                                                    )      );

        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "40%" );
        $this->ipsclass->adskin->td_header[] = array( "&nbsp;"  , "60%" );

        $this->ipsclass->html .= $this->ipsclass->adskin->start_table( 'Required' );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Vehicle Model to Delete: </b>" , $name ) );

        $this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array( "<b>Change all <i>existing vehicles of this Model(s)</i> to which Model?</b>" ,
                                                                             $this->ipsclass->adskin->form_dropdown( "move_model_id", $models_array )
                                                                    )      );

        $this->ipsclass->html .= $this->ipsclass->adskin->end_form("Update Vehicles and delete the Model(s)");

        $this->ipsclass->html .= $this->ipsclass->adskin->end_table();

        $this->ipsclass->admin->nav[] = array( 'act='.REGISTRY_URL.'&section=components&menu=makes_models', 'Fusion Registry Makes' );

        $this->ipsclass->admin->nav[] = array( 'act='.REGISTRY_URL.'&section=components&menu=makes_models', 'Fusion Registry Vehicle Makes' );
        $this->ipsclass->admin->nav[] = array( '', 'Delete Model(s)' );

        // That's all folks!
        $this->ipsclass->admin->output();
    }


    /**
     * Delete a vehicle model(s)
     *
     * Multiple values are split on ',' (comma)
     */
    function delete_model()
    {
        // Do we have a valid source?
        if ($this->ipsclass->input['model_id'] == "")
        {
            $this->ipsclass->admin->error("Could not determine the source Fusion Registry Vehicle Model ID.");
        }

        // How about a valid destination?
        if ($this->ipsclass->input['move_model_id'] == "")
        {
            $this->ipsclass->admin->error("Could not determine the destination Fusion Registry Vehicle Model ID.");
        }

        // Extract possible multi-ids
        $model_ids = explode(',', $this->ipsclass->input['model_id']);

        // Make our sql safe ID list
        $sql_model_ids = "('". implode("','", $model_ids) ."')";

        // Grab the Model being deleted
        $this->ipsclass->DB->query("SELECT model FROM ibf_registry_models WHERE id IN $sql_model_ids");

        $model_to_delete = '';

        while ( $row = $this->ipsclass->DB->fetch_row() )
        {
            $model_to_delete .= $row['model'] .', ';
        }

        $model_to_delete = substr($model_to_delete, 0, -2);

        // Get our custom field def for the model field
        $cf_def = $this->lib['custom_fields']->get_cf_defs( array('WHERE' => "field_options='model'") );

        // It will/should be are first and only returned value!
        $model_def = array_shift($cf_def);

        // Update the existing Vehicles
        $this->ipsclass->DB->query("UPDATE ibf_registry_field_entries SET field_value='".$this->ipsclass->input['move_model_id']."'
                                    WHERE field_value IN $sql_model_ids AND field_id='". $model_def['field_id'] ."'");

        // Bye-Bye... delete the model
        $this->ipsclass->DB->query("DELETE FROM ibf_registry_models WHERE id IN $sql_model_ids");

        $text = "Deleted Fusion Registry Vehicle Model '$model_to_delete'";
        $url = 'act='.REGISTRY_URL.'&section=components&menu=makes_models&code=model_menu&make_id='. $this->ipsclass->input['make_id'];
        $time = 2;

        // Big brother is watching :)
        $this->ipsclass->admin->save_log($text);

        // End of the show, c'ya
        $this->ipsclass->admin->redirect( $url, $text, 0, $time );
    }
}